<script setup lang="ts">
import {ref, watch} from "vue";
interface ITaskItem{
  id: number;
  text: string;
  isDone: boolean;
  isEdit: boolean
}
let todoText = ref('');

let taskList = ref<ITaskItem[]>([]);

taskList.value=JSON.parse(
    window.localStorage.getItem('taskList')??"[]"
);//反串行化

watch(taskList, onSave, {deep:true});
function  onAddTask(){
  taskList.value.push({
    id: taskList.value.length + 1,
    text: todoText.value,
    isDone: false,
    isEdit: false
  });
  todoText.value = ''; //当输入完待办事项添加之后，框里清空

  window.localStorage
      .setItem('taskList',JSON.stringify(taskList.value))
            //key-value 结构(串行化)
}
function onSave() {
  window.localStorage
      .setItem('taskList',JSON.stringify(taskList.value))
  //key-value 结构(串行化)

}
let itemText = ref("");
function onEdit(item: ITaskItem){
  item.isEdit = true;
  itemText.value = item.text;
}
function onEditOk(item: ITaskItem){
  item.isEdit = false;
  item.text=itemText.value;
}
function onDelete(item: ITaskItem){
  taskList.value = taskList.value.filter(it=>it!==item)
}


</script>

<template>
     <div class="container">
       <h1>ToDo List</h1>
       <div class="input-row">
         <el-input style="width:20em" placeholder="请输入一个待办事项..." v-model="todoText" />
       <!--  -->
         <el-button type="success" @click="onAddTask">添加</el-button>
       </div>

       <div class="task-list">
         <div v-for="item of taskList" class="task-item">
           <template v-if="!item.isEdit">
           <el-checkbox v-model="item.isDone" size="large">{{item.text}}</el-checkbox>
          <div class="">
            <el-button type="primary" @click="onEdit(item)">修改</el-button>
            <el-button type="danger" @click="onDelete(item)">删除</el-button>
          </div>
           </template>
           <template v-else>
             <el-checkbox v-model="item.isDone" size="large">
               <el-input v-model="itemText"></el-input>
               <el-button @click="onEditOk(item)">确定</el-button>
               <el-button @click="item.isEdit=false">取消</el-button>
             </el-checkbox>
           </template>
         </div>

       </div>

     </div>
</template>

<style scoped>
.container{
  display: flex;
  flex-direction: column;
  height: 100vh;
  width:80%;
  margin: 0 auto;   /*auto左右边距设置成自动*/
  background-color: #f3f3f3;
}
h1{
  text-align: center; /*居中*/
  margin-top: 20px;
}

.input-row {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 0.5em; /*让输入框和按钮之间有空隙*/
}

.task-list{
  padding:0 2em;
}
.task-item{
  display:flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ccc;
}
</style>
